package listening_function;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ID_add {
    static Connection conn = null;
	static Statement stmt = null;
	static ResultSet rs = null;

	public static int ID_next(String tablename) {
		int nextID = 0;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/orcl", "Amy", "123");
			stmt = conn.createStatement();
			String sql = "select id from "+tablename+" order by id";
			rs = stmt.executeQuery(sql);
			
			int [] id = new  int [100];
			int i = 0;
			while(rs.next()){
				id[i] = rs.getInt(1);
				System.out.print(id[i]+" ");
				i++;
			}
			
			for(i = 0; i < id.length; i++){
				if(id[i+1]!=id[i]+1){
					nextID = id[i]+1;
					break;
				}
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return nextID;
	}
}
